<template>
  <div class="app-container">

    <!-- 顶部查询表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="100px">
      <el-form-item label="单据时间" prop="documentTime">
        <el-select v-model="queryParams.documentTimeRange" placeholder="最近7日" style="width: 120px">
          <el-option label="最近7日" value="7days"/>
          <el-option label="最近30日" value="30days"/>
          <el-option label="最近90日" value="90days"/>
          <el-option label="自定义" value="custom"/>
        </el-select>
      </el-form-item>
      <el-form-item label="发货单号" prop="deliveryCode">
        <el-input v-model="queryParams.deliveryCode" placeholder="请输入发货单号" clearable/>
      </el-form-item>
      <el-form-item label="店铺名称" prop="shopName">
        <el-input v-model="queryParams.shopName" placeholder="请输入店铺名称" clearable/>
      </el-form-item>
      <el-form-item label="会员名称" prop="memberName">
        <el-input v-model="queryParams.memberName" placeholder="请输入会员名称" clearable/>
      </el-form-item>
      <el-form-item label="平台单号" prop="platformOrderCode">
        <el-input v-model="queryParams.platformOrderCode" placeholder="请输入平台单号" clearable/>
      </el-form-item>
      <el-form-item label="合作名称" prop="partnerName">
        <el-input v-model="queryParams.partnerName" placeholder="请输入合作名称" clearable/>
      </el-form-item>
      <el-form-item label="物流公司" prop="expressCompany">
        <el-select v-model="queryParams.expressCompany" placeholder="通宏物流" clearable style="width: 120px">
          <el-option label="通宏物流" value="TH"/>
          <el-option label="顺丰快递" value="SF"/>
          <el-option label="圆通快递" value="YT"/>
        </el-select>
      </el-form-item>
      <el-form-item label="物流单号" prop="expressNumber">
        <el-input v-model="queryParams.expressNumber" placeholder="请输入物流单号" clearable/>
      </el-form-item>
      <el-form-item label="平台类型" prop="platformType">
        <el-input v-model="queryParams.platformType" placeholder="请输入平台类型" clearable/>
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="queryParams.isRefund">退款</el-checkbox>
        <el-checkbox v-model="queryParams.hasLogisticsLabel">物流单打印</el-checkbox>
        <el-checkbox v-model="queryParams.hasElectronicBill">电子面单</el-checkbox>
        <el-checkbox v-model="queryParams.isIntercept">拦截挂起</el-checkbox>
        <el-checkbox v-model="queryParams.isShipped">发货</el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮组 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
         <el-button type="primary" size="mini">
            发货单打印<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain size="mini" icon="el-icon-edit" @click="handleModify">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain size="mini" icon="el-icon-edit-outline" @click="handleBatchModify" >批量修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain size="mini" icon="el-icon-truck" @click="handleBatchModifyExpress">批量修改物流公司</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain size="mini" icon="el-icon-box" @click="handleMultiPackage">多包装</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain size="mini" icon="el-icon-close" @click="handleInvalidate">作废</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain size="mini" icon="el-icon-delete" @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain size="mini" icon="el-icon-edit" @click="handleFillExpressNo">填充物流单号</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain size="mini" icon="el-icon-truck" @click="handleShip">发货</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button icon="el-icon-refresh" size="mini" @click="handleRefresh">刷新</el-button>
      </el-col>
    </el-row>

    <!-- 主表格 -->
    <vxe-table
      border
      stripe
      v-loading="loading"
      ref="mainTable"
      size="small"
      header-align="center"
      :data="mainTableData"
      @checkbox-change="mainCheckboxChange"
      @checkbox-all="mainCheckboxAll"
      @cell-click="cellClickEvent"
    >
      <vxe-column type="seq" title="序号" width="50" fixed="left" />
      <vxe-column field="shipStatus" title="发货状态" align="center" width="80" fixed="left">
        <template v-slot="{ row }">
          <el-tag v-if="row.shipStatus === 'LOCKED'" type="danger" size="mini">锁</el-tag>
          <span v-else>{{ row.shipStatus === 'SHIPPED' ? '已发货' : '未发货' }}</span>
        </template>
      </vxe-column>
      <vxe-column field="hasDeliveryLabel" title="发货单打印" align="center" width="90">
        <template v-slot="{ row }">
          <el-checkbox v-model="row.hasDeliveryLabel" disabled />
        </template>
      </vxe-column>
      <vxe-column field="hasLogisticsLabel" title="物流单打印" align="center" width="90">
        <template v-slot="{ row }">
          <el-checkbox v-model="row.hasLogisticsLabel" disabled />
        </template>
      </vxe-column>
      <vxe-column field="hasElectronicBill" title="电子面单" align="center" width="80">
        <template v-slot="{ row }">
          <el-checkbox v-model="row.hasElectronicBill" disabled />
        </template>
      </vxe-column>
      <vxe-column field="deliveryCode" title="发货单号" align="center" width="140" />
      <vxe-column field="logisticsCode" title="物流单号" align="center" width="140" />
      <vxe-column field="logisticsSerialNo" title="物流单打印处-流水号" align="center" width="150" />
      <vxe-column field="deliverySerialNo" title="发货单打印处-流水号" align="center" width="150" />
      <vxe-column field="itemQuantity" title="商品数量" align="center" width="80" />
      <vxe-column field="packageCount" title="包裹数" align="center" width="70" />
      <vxe-column field="parentPackage" title="母件" align="center" width="80">
        <template v-slot="{ row }">
          <span v-if="row.parentPackage">多包裹</span>
        </template>
      </vxe-column>
      <vxe-column field="memberName" title="会员" align="center" width="100" />
      <vxe-column field="isRefund" title="退款" align="center" width="60">
        <template v-slot="{ row }">
          <el-tag v-if="row.isRefund" type="warning" size="mini">退款</el-tag>
        </template>
      </vxe-column>
      <vxe-column field="shopName" title="店铺" align="center" width="120" />
      <vxe-column field="logisticsCompany" title="物流公司" align="center" width="100" />
      <vxe-column field="insuranceAmount" title="皮收金额" align="center" width="80">
        <template v-slot="{ row }">
          {{ row.insuranceAmount || '0' }}
        </template>
      </vxe-column>
      <vxe-column field="buyerRemark" title="买家留言" align="center" width="120" show-overflow />
      <vxe-column field="sellerRemark" title="卖家留言" align="center" width="120" show-overflow />
      <vxe-column field="receiver" title="收件人" align="center" width="80" />
      <vxe-column field="itemName" title="商品名称" align="center" min-width="150" show-overflow />
      <vxe-column field="warehouse" title="仓库" align="center" width="100" />
      <vxe-column field="financialAuditor" title="财审人" align="center" width="80" />
      <vxe-column field="receiverPhone" title="收货人手机" align="center" width="120" />
      <vxe-column field="receiverAddress" title="收货地址" align="center" width="200" show-overflow />
      <vxe-column field="picker" title="配货人" align="center" width="80" />
      <vxe-column field="pickingTime" title="配货时间" align="center" width="150" />
      <vxe-column field="paymentTime" title="支付时间" align="center" width="150" />
      <vxe-column field="parentWaybillNo" title="母运单号" align="center" width="140" />
    </vxe-table>
     
    <!-- 主表格分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 底部Tab区域 -->
    <div class="app-container-footer">
        <el-tabs v-model="activeTab" type="border-card">
          <el-tab-pane label="订单明细" name="orderDetail">
            <OrderDetail :deliveryOrderId="currentCellId" />
          </el-tab-pane>
          <el-tab-pane label="商品明细" name="itemDetail">
            <ItemDetail :deliveryOrderId="currentCellId" />
          </el-tab-pane>
          <el-tab-pane label="收货信息" name="receiverInfo">
            <ReceiverInfo :deliveryOrderId="currentCellId" />
          </el-tab-pane>
          <el-tab-pane label="包裹信息" name="packageInfo">
            <PackageInfo :deliveryOrderId="currentCellId" />
          </el-tab-pane>
          <el-tab-pane label="订单日志" name="orderLog">
            <OrderLog :deliveryOrderId="currentCellId" />
          </el-tab-pane>
          <el-tab-pane label="操作日志" name="opLog">
            <OpLog :deliveryOrderId="currentCellId" />
          </el-tab-pane>
        </el-tabs>
    </div>
  </div>
</template>

<script>
import OrderDetail from './components/orderDetail.vue';
import ItemDetail from './components/itemDetail.vue';
import ReceiverInfo from './components/receiverInfo.vue';
import PackageInfo from './components/packageInfos.vue';
import OrderLog from './components/orderLog.vue';
import OpLog from './components/opLog.vue';

import { listPrepare } from "@/api/mes/sales/prepare";


export default {
  name: "Prepare",
  components: {
    OrderDetail,
    ItemDetail,
    ReceiverInfo,
    PackageInfo,
    OrderLog,
    OpLog
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        documentTimeRange: '7days', // 单据时间范围选择
        deliveryCode: undefined, // 发货单号
        shopName: undefined, // 店铺名称
        memberName: undefined, // 会员名称
        platformOrderCode: undefined, // 平台单号
        partnerName: undefined, // 合作名称
        expressCompany: undefined, // 物流公司
        expressNumber: undefined, // 物流单号
        platformType: undefined, // 平台类型
        // 复选框标记
        isRefund: false, // 退款
        hasLogisticsLabel: false, // 物流单打印
        hasElectronicBill: false, // 电子面单
        isIntercept: false, // 拦截挂起
        isShipped: false, // 发货
      },
      // 店铺选项
      shopOptions: [],
      // 主表格数据
      mainTableData: [],
      // 底部Tab
      activeTab: 'orderDetail',
      // 当前选中行ID
      currentCellId: null,

    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 处理作废操作 */
    handleVoid() {
      if (!this.ids || this.ids.length === 0) {
        this.$modal.msgError('请选择要作废的数据');
        return;
      }
      this.$confirm('确认要作废选中的记录吗？', '警告', {
        type: 'warning'
      }).then(() => {
        // TODO: 调用作废接口
        // voidDelivery(this.ids).then(response => {
        //   this.$modal.msgSuccess('作废成功');
        //   this.getList();
        // });
        this.$modal.msgSuccess('作废成功');
        this.getList();
      }).catch(() => {});
    },

    /** 远程搜索店铺 */
    remoteShopSearch(query) {
      if (query) {
        // TODO: 调用店铺搜索接口
        // searchShops(query).then(response => {
        //   this.shopOptions = response.data.map(item => ({
        //     value: item.id,
        //     label: item.name
        //   }));
        // });
        
        // 临时使用模拟数据
        this.shopOptions = [
          { value: '1', label: '店铺A' },
          { value: '2', label: '店铺B' },
          { value: '3', label: '店铺C' }
        ].filter(item => item.label.toLowerCase().includes(query.toLowerCase()));
      } else {
        this.shopOptions = [];
      }
    },

    /** 查询列表 */
    getList() {
      this.loading = true;
      listPrepare(this.queryParams)
        .then(response => {
          // 兼容后端返回格式，假设 response.rows 为数据数组，response.total 为总数
          this.mainTableData = (response.rows || []).map(item => ({
            id: item.id,
            shipStatus: item.shipStatus || 'NOT_SHIPPED', // 发货状态：LOCKED/SHIPPED/NOT_SHIPPED
            hasDeliveryLabel: item.hasDeliveryLabel || false, // 发货单打印
            hasLogisticsLabel: item.hasLogisticsLabel || false, // 物流单打印
            hasElectronicBill: item.hasElectronicBill || false, // 电子面单
            deliveryCode: item.deliveryCode, // 发货单号
            logisticsCode: item.logisticsCode, // 物流单号
            logisticsSerialNo: item.logisticsSerialNo, // 物流单打印处-流水号
            deliverySerialNo: item.deliverySerialNo, // 发货单打印处-流水号
            itemQuantity: item.itemQuantity || 0, // 商品数量
            packageCount: item.packageCount || 1, // 包裹数
            parentPackage: item.parentPackage || false, // 母件标记
            memberName: item.memberName, // 会员
            isRefund: item.isRefund || false, // 退款标记
            shopName: item.shopName, // 店铺
            logisticsCompany: item.logisticsCompany, // 物流公司
            insuranceAmount: item.insuranceAmount || 0, // 皮收金额
            buyerRemark: item.buyerRemark, // 买家留言
            sellerRemark: item.sellerRemark, // 卖家留言
            receiver: item.receiver, // 收件人
            itemName: item.itemName, // 商品名称
            warehouse: item.warehouse, // 仓库
            financialAuditor: item.financialAuditor, // 财审人
            receiverPhone: item.receiverPhone, // 收货人手机
            receiverAddress: item.receiverAddress, // 收货地址
            picker: item.picker, // 配货人
            pickingTime: item.pickingTime, // 配货时间
            paymentTime: item.paymentTime, // 支付时间
            parentWaybillNo: item.parentWaybillNo, // 母运单号
            buyer: item.buyer,
            receiver: item.receiver,
            deliveryAddress: item.deliveryAddress,
            deliveryPerson: item.deliveryPerson,
            deliveryTime: item.deliveryTime,
            insuranceAmount: item.insuranceAmount
          }));
          this.total = response.total || 0;
          this.loading = false;
          if (this.mainTableData.length > 0) {
            this.$refs.mainTable.setCurrentRow(this.mainTableData[0]);
            this.cellClickEvent({ row: this.mainTableData[0] });
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 主表格 Checkbox 事件 */
    mainCheckboxChange({ records }) {
      this.ids = records.map(item => item.id);
    },
    mainCheckboxAll({ records }) {
      this.ids = records.map(item => item.id);
    },
    /** 单元格点击事件 */
    cellClickEvent({ row }) {
      if (row && row.id !== this.currentCellId) {
        this.currentCellId = row.id;
      }
    },

    /** 批量打印操作 */
    handleBatchPrint(command) {
      if (!this.ids || this.ids.length === 0) {
        this.$message.warning('请选择要打印的记录');
        return;
      }
      if (command === 'delivery') {
        // TODO: 调用发货单打印接口
        this.$message.success('开始打印发货单');
      } else if (command === 'logistics') {
        // TODO: 调用物流单打印接口
        this.$message.success('开始打印物流单');
      }
    },

    /** 修改按钮操作 */
    handleModify() {
      const row = this.$refs.mainTable.getCheckboxRecords()[0];
      if (!row) {
        this.$message.warning('请选择要修改的记录');
        return;
      }
      // TODO: 打开修改对话框
      this.$message.success('打开修改对话框');
    },

    /** 批量修改按钮操作 */
    handleBatchModify() {
      if (!this.ids || this.ids.length === 0) {
        this.$message.warning('请选择要修改的记录');
        return;
      }
      // TODO: 打开批量修改对话框
      this.$message.success('打开批量修改对话框');
    },

    /** 批量修改物流公司操作 */
    handleBatchModifyExpress() {
      if (!this.ids || this.ids.length === 0) {
        this.$message.warning('请选择要修改的记录');
        return;
      }
      // TODO: 打开批量修改物流公司对话框
      this.$message.success('打开批量修改物流公司对话框');
    },

    /** 多包装操作 */
    handleMultiPackage() {
      const row = this.$refs.mainTable.getCheckboxRecords()[0];
      if (!row) {
        this.$message.warning('请选择要处理的记录');
        return;
      }
      // TODO: 打开多包装对话框
      this.$message.success('打开多包装对话框');
    },

    /** 作废操作 */
    handleInvalidate() {
      if (!this.ids || this.ids.length === 0) {
        this.$message.warning('请选择要作废的记录');
        return;
      }
      this.$confirm('确认要作废选中的记录吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // TODO: 调用作废接口
        this.$message.success('作废成功');
      });
    },

    /** 删除操作 */
    handleDelete() {
      if (!this.ids || this.ids.length === 0) {
        this.$message.warning('请选择要删除的记录');
        return;
      }
      this.$confirm('确认要删除选中的记录吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // TODO: 调用删除接口
        this.$message.success('删除成功');
      });
    },

    /** 填充物流单号操作 */
    handleFillExpressNo() {
      if (!this.ids || this.ids.length === 0) {
        this.$message.warning('请选择要填充物流单号的记录');
        return;
      }
      // TODO: 调用填充物流单号接口
      this.$message.success('填充物流单号成功');
    },

    /** 发货操作 */
    handleShip() {
      if (!this.ids || this.ids.length === 0) {
        this.$message.warning('请选择要发货的记录');
        return;
      }
      this.$confirm('确认要发货选中的记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        // TODO: 调用发货接口
        this.$message.success('发货成功');
      });
    },

    /** 刷新操作 */
    handleRefresh() {
      this.getList();
    }

  }
};
</script>

<style lang="scss" scoped>
.app-container-footer {
  margin-top: 20px;
}
.mb8 {
  margin-bottom: 8px;
}
</style>
